package com.kakarote.crm9.erp.jxc.service;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.kakarote.crm9.erp.jxc.entity.GoodsSuppliers;
import com.kakarote.crm9.erp.jxc.entity.ProcurementNumber;
import com.kakarote.crm9.erp.jxc.entity.ProcurementOrder;
import com.kakarote.crm9.erp.jxc.entity.ProcurementOrderDetails;
import com.kakarote.crm9.utils.*;
import net.sf.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：青苔 1046600124
 * @date ：Created in 2021-03-16 16:06
 * @description：
 * @modified By：`
 * @version: 1.0
 */
public class ProcurementOrderService {

    /**
     * 查询采购订单列表
     * @param pd
     * @return
     */
    public List<Record> list(PageData pd){
        int pageNum = pd.get("pageNum",Integer.class);
        int pageSize = pd.get("pageSize",Integer.class);
        pageNum = (pageNum-1)*pageSize;
        String sql = Db.getSql("jxc.ProcurementOrder.queryList");
        try {
            SqlUtil sqlUtil = new SqlUtil();
            String convertSql = sqlUtil.convert(sql, pd);
            List<Object> params = sqlUtil.getParams();
            if (params != null && params.size() > 0) {
                params.add(pageNum);
                params.add(pageSize);
                return Db.find(convertSql, params.toArray());
            }
            return Db.find(convertSql, pageNum, pageSize);

        }catch (Exception e){
            return null;
        }

    }

    /**
     * 根据采购订单id查询
     * @param id
     * @return
     */
    public Record getInfo(Integer id){
        return Db.findFirst(Db.getSql("jxc.ProcurementOrder.queryId"),id);
    }

    /**
     * 新增采购订单
     * @param pd
     * @return
     */
    @Before(Tx.class)
    public R add(PageData pd){

        R parameter = parameter(pd);
        if(parameter.get("code").toString().equals("0")){
            ProcurementOrder data =(ProcurementOrder) parameter.get("data");
            Object id = data.get("id");
            parameter = addprocurementOrderDetails(JSON.parseObject(pd.get("orderList").toString(),List.class),id);
        }
        return parameter;
    }


    /**
     * 修改采购订单信息
     * @param pd
     * @return
     */
    public R edit(PageData pd){
        R parameter = parameter(pd);
        if(parameter.get("code").toString().equals("0")){
            List list =removeprocurementOrderDetails(JSON.parseObject(pd.get("orderList").toString(), List.class));
            ProcurementOrder data =(ProcurementOrder) parameter.get("data");
            Object id = data.get("id");
            parameter = addprocurementOrderDetails(list,id);
        }
        return parameter;
    }

    /**
     * 删除采购订单
     * @param ids
     * @return
     */
    public R remove(List<String> ids){
        ProcurementOrder suppliers = new ProcurementOrder();
        int temp=0;
        for (String id : ids) {
            if(id!=null &&!id.equals("")){
                temp+= Db.delete(Db.getSql("jxc.ProcurementOrder.deleteSuppliersById"),id);
            }
        }
        return temp > 0 ? R.ok() : R.error("删除失败");
    }

    /**
     * 封装新增修改的数据
     * @param pd
     * @return
     */
    private R parameter (PageData pd){
        if(pd.get("suppliersId")==null) return R.error("请选择供应商名称");
        if(pd.get("totalNum")==null) return R.error("合计不能为空");
        if(pd.get("totalPrice")==null) return R.error("总金额不能为空");
        if(pd.get("buyTime")==null) return R.error("单据日期不能为空");
        if(pd.get("deliveryTime")==null) return R.error("交货日期不能为空");
        if(pd.get("PreferentialLastPrice")==null) return R.error("优惠后金额不能为空");
        if(pd.get("type")==null) return R.error("类型不能为空");

        ProcurementOrder suppliers = new ProcurementOrder();
        suppliers.set("suppliers_id",pd.get("suppliersId"))
                .set("total_num",pd.get("totalNum"))
                .set("total_price",pd.get("totalPrice"))
                .set("buy_time",pd.get("buyTime"))
                .set("delivery_time",pd.get("deliveryTime"))
                .set("Preferential_last_price",pd.get("PreferentialLastPrice"))

                .set("type",pd.get("type"));


        if(pd.get("id")!=null)suppliers.set("id",pd.get("id"));
        if(pd.get("remark")!=null&&!pd.get("remark",String.class).equals(""))suppliers.set("remark",pd.get("remark"));
        if(pd.get("PreferentialRate")!=null&&!pd.get("PreferentialRate",String.class).equals(""))suppliers.set("Preferential_rate",pd.get("PreferentialRate"));
        if(pd.get("PreferentialPrice")!=null&&!pd.get("PreferentialPrice",String.class).equals(""))suppliers.set("Preferential_price",pd.get("PreferentialPrice"));
        if(pd.get("itemId")!=null&&!pd.get("itemId",String.class).equals(""))suppliers.set("item_id",pd.get("itemId"));
        if(pd.get("name")!=null&&!pd.get("name",String.class).equals(""))suppliers.set("name",pd.get("name"));
        if(pd.get("orderUser")!=null&&!pd.get("orderUser",String.class).equals(""))suppliers.set("order_user",pd.get("orderUser"));

        if(pd.get("id")==null){

            suppliers .set("order_coding",procurementNumber(pd.get("orderDate").toString()))
                    .set("create_by", BaseUtil.getUser().getUsername())
                    .set("create_time",new Date());
            return suppliers.save()?R.ok().put("data",suppliers):R.error("新增失败");
        }else {
            return suppliers.update()?R.ok().put("data",suppliers):R.error("修改失败");
        }

    }

    /**
     * 新增修改订单详情
     * @param list
     * @return
     */
    private R addprocurementOrderDetails(List list,Object id){
        R r = null;
        if(list!=null&&list.size()>0&&id!=null){
            for (Object o : list) {
                if (o instanceof  Map) {
                    ProcurementOrderDetails details = new ProcurementOrderDetails();
                    details.set("order_id",id);
                    details.set("categorie_id",((Map) o).get("categorieId"));
                    details.set("specification",((Map) o).get("specification"));
                    details.set("warehouse_id",((Map) o).get("warehouseId"));
                    details.set("unit",((Map) o).get("unit"));
                    details.set("number",((Map) o).get("number"));
                    details.set("price",((Map) o).get("price"));
                    details.set("total",((Map) o).get("total"));
                    details.set("goods_type",((Map) o).get("goodsType"));
                    if(((Map) o).get("discountRate")!=null) details.set("",((Map) o).get("discountRate"));
                    if(((Map) o).get("discountPrice")!=null) details.set("",((Map) o).get("discountPrice"));
                    if(((Map) o).get("remark")!=null) details.set("remark",((Map) o).get("remark"));
                    if(((Map) o).get("id")!=null){
                        details.set("id",((Map) o).get("id"));
                       r =  details.update()?R.ok():R.error();
                    }else{
                        details .set("create_by", BaseUtil.getUser().getUsername())
                                .set("create_time",new Date());
                        r =  details.save()?R.ok():R.error();
                    }
                }else{
                    r = R.error("参数不完整");
                }
            }
        }else{
            r = R.error("参数不完整");
        }
        return r;
    }

    /**
     * 删除订单详情
     * @param list
     * @return
     */
    private List removeprocurementOrderDetails(List list){

        ProcurementOrderDetails details = new ProcurementOrderDetails();
        int temp = 0;
        for (Object o : list) {
            if(o instanceof Map){
                Object id  = ((Map) o).get("id");
                if(id!=null){
                    temp+= Db.delete(Db.getSql("jxc.ProcurementOrderDetails.delete"),id);
                    ((Map) o).remove("id");
                }
            }
        }
        return list;
    }
    /**
     * 获取当前时间最大的编号
     * @param date
     * @return 返回最大数+1 作为采购管理最大的后缀
     */
    private String procurementNumber(String date){
        int flag = 0;
        ProcurementNumber number =new ProcurementNumber();
        String order = "CGDD" + date;
        List<ProcurementNumber> buyTime = number.find(Db.getSql("jxc.ProcurementNumber.queryList"),order);
        if(buyTime!=null&&buyTime.size()>0){
            ProcurementNumber p = buyTime.get(0);
            flag = Integer.parseInt(p.get("number").toString())+1;
            p.set("number",flag);
            p.update();
        }else{
            number.set("date",order);
            number.set("number",flag+1);
            number.save();
            flag = 1;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(order);
        if(flag<10){
            stringBuilder.append("00").append(flag);
        }else if(flag<100){
            stringBuilder.append("0").append(flag);
        }else if(flag<1000){
            stringBuilder.append(flag);
        }
        return stringBuilder.toString();
    }

}
